package com.deepexi.sample.controller;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.*;

@RestController
public class RedissonController {

    @Resource
    private RedissonClient redissonClient;

    @ResponseBody
    @RequestMapping(value = "redisson")
    public String redisson() {
        final int[] amount = {1000};
        CountDownLatch latch = new CountDownLatch(1000);
        RLock lock = redissonClient.getLock("lock_key");

        //核心线程数
        int corePoolSize = 8;
        //最大线程数
        int maximumPoolSize = 32;
        //超过 corePoolSize 线程数量的线程最大空闲时间
        long keepAliveTime = 2;
        //以秒为时间单位
        TimeUnit unit = TimeUnit.SECONDS;
        //创建工作队列，用于存放提交的等待执行任务
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(1000);
        ThreadPoolExecutor threadPoolExecutor = null;
        try {
            //创建线程池
            threadPoolExecutor = new ThreadPoolExecutor(corePoolSize,
                    maximumPoolSize,
                    keepAliveTime,
                    unit,
                    workQueue,
                    new ThreadPoolExecutor.AbortPolicy());

            for (int i = 0; i < 1000; i++) {
                threadPoolExecutor.submit(() -> {
                    // 不加锁
                    // amount[0]--;

                    // 加锁
                    boolean res;
                    try {
                        res = lock.tryLock(100, 10, TimeUnit.SECONDS);
                        if(res){
                            amount[0]--;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally{
                        lock.unlock();
                    }

                    latch.countDown();
                });
            }

            latch.await();
            return "amount:" + amount[0];

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (threadPoolExecutor != null) {
                threadPoolExecutor.shutdown();
            }
        }

        return "end";
    }
}
